<?php namespace Home\Controller; 

use Hdphp\Controller\Controller;
// use Home\Model\Cart;

class CartController extends Controller
{
	// protected $db;

	//构造函数
	public function __init()
	{

		// $this->db = new Cart;
	}
	
    //购物车页面
    public function cart(){
         // echo header("Access-Control-Allow-Origin: *");    
    	if(IS_POST){
            if($c = $_POST){
                $cart = Db::table('shop_goods')->where('goods_id',$c['goods_id'])->first();
                $total = $c['cartnum'];
                $price = $cart['price'] * $total;
                $_SESSION['confirm'][$c['goods_id']]['minprice'] = $price;
                $_SESSION['confirm'][$c['goods_id']]['total'] = $total;
                View::ajax(array('price'=>$price,'total'=>$total));

            }else{
                View::ajax(array('code'=>0,'message'=>'操作失败'));
            }
        }else{
            $userid = !empty($_SESSION['id'])?$_SESSION['id']:'0';
            echo header("Access-Control-Allow-Origin: *");
            if(!isset($_SESSION['joinCart']) || count($_SESSION['joinCart'])==0){
                View::with('userid',$userid);
                View::make('nullCart');
            }            
            //定义数组
            $data = array();
            // 遍历缓存中的商品
            foreach ($_SESSION['joinCart'] as $key => $value) {
                $cart = Db::table('shop_goods')->where('goods_id',$value['goods_id'])->first();
                $cart['size'] = $value['size'];
                $cart['total'] = $value['cartnum'];
                $cart['minprice'] = isset($value['minprice'])?$value['minprice']:$cart['price'];
                $data[$key] = $cart;
            }
            $_SESSION['confirm'] = $data;           
            // 赋值模版
            View::with('userid',$userid);
            View::with('data',$data);
            View::make();
        }        
    }
    //购物车数据
    public function joinCart()    
    {
        // echo header("Access-Control-Allow-Origin: *");     
    	if(IS_POST)
    	{
            $_SESSION['joinCart'][$_POST['goods_id']] = $_POST;         
            if(!isset($_POST['minprice']))
            {
                if($cartNum = count($_SESSION['joinCart'])){
                    View::ajax(array('code'=>1,'message'=>'加入购物车成功','cartNum'=>$cartNum));
                }else{
                    View::ajax(array('code'=>0,'message'=>'操作失败','cartNum'=>$cartNum));
                }
            }
        }
    }

    //删除购物车单条数据
    public function del()
    {
        if(IS_POST)
        {
            $key = Q('del_id');
            unset($_SESSION['joinCart'][$key]);
            View::ajax(array('code'=>1));
        }    	
    }
}
